import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import LoginVue from '../views/Login/index.vue'
import { userInfoApi } from '../http/api'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'
const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        component: LoginVue
    },
    {
        path: "/",
        component: () => import("../views/Home/Index.vue"),
        redirect: "/index",
        children: [
            {
                path: "index",
                component: () => import("../views/Index/Index.vue"),
            }
        ]
    },
    // {
    //     path: "/ums",
    //     component: () => import("../views/Home/Index.vue"),
    //     children: [
    //         {
    //             path: "admin",
    //             component: LoginVue,
    //         }
    //     ]
    // },
]

const router = createRouter({
    routes,
    history: createWebHashHistory()
})
router.beforeEach((to, from, next) => {
    const store = useUserStore()
    let token = localStorage.getItem("token")
    if (store.menus.length == 0 && token) {
        userInfoApi().then(res => {
            // console.log(res);
            if (res.code === 200) {

                store.menus = res.data.menus
                store.username = res.data.username
                // 动态添加路由
                store.routes.forEach(p => {
                    const route: RouteRecordRaw = {
                        path: "/" + p.name,
                        name: p.name,
                        meta: {
                            title: p.title
                        },
                        component: () => import("../views/Home/Index.vue"),
                        children: p.children.map(item => ({
                            path: item.name,
                            name: item.name,
                            meta: {
                                title: item.title
                            },
                            component: () => import(`../views/${p.name}/${item.name}.vue`)
                        }))

                    }
                    if(p.children[0]){
                        route.redirect = `/${p.name}/${p.children[0].name}`;
                    }
                    router.addRoute(route)
                })
                next(to.fullPath)
            }
        })
    } else if (!token && to.path !== '/login') {
        ElMessage.error("亲！登录已过期请重新登录")
        next("/login")
    } else if (token && to.path == '/login' && store.menus.length !== 0) {
        ElMessage.warning("亲！请先退出登录")
        next(from.fullPath)
    }
    else {
        next()
    }
})
export default router